package com.distributer.timer.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Service;

import com.distributer.timer.job.ScheduledTaskJob;
import com.distributer.timer.mapper.ScheduledTaskMapper;
import com.distributer.timer.model.ScheduledTask;
import com.distributer.timer.service.ScheduledTaskService;

@Service
public class ScheduledTaskServiceImpl implements ScheduledTaskService{

	private final static Logger LOGGER = LoggerFactory.getLogger(ScheduledTaskServiceImpl.class);
	
	@Autowired
	private ScheduledTaskMapper scheduledTaskMapper;
	@Autowired 
	private ThreadPoolTaskScheduler threadPoolTaskScheduler;
	@Value("${clientId}")
	private String clientId;

	private AtomicBoolean startedFlag = new AtomicBoolean(false);
	
	private Map<String, ScheduledTaskJob> scheduledTaskJobs = new ConcurrentHashMap<String, ScheduledTaskJob>();
	
	@Override
	public void initAllTask() {
		if (startedFlag.get()) {
			return;
		}
		List<ScheduledTask> allScheduledTasks = scheduledTaskMapper.findAllScheduledTasks();
		for (ScheduledTask scheduledTask : allScheduledTasks) {
			doStartTask(scheduledTask);
		}
		startedFlag.compareAndSet(false, true);
		LOGGER.info("定时任务启动成功...");
	}
	
	@Override
	public void stopAllTask() {
		for (Entry<String, ScheduledTaskJob> entry : scheduledTaskJobs.entrySet()) {
			entry.getValue().getScheduledTask().updateTaskToStop();
		}
		threadPoolTaskScheduler.shutdown();
	}
	
	/**
	 *	启动定时任务
	 * @param scheduledTask
	 */
    private void doStartTask(ScheduledTask scheduledTask) {
        //获取需要定时调度的接口
        ScheduledTaskJob scheduledTaskJob = new ScheduledTaskJob(scheduledTask,clientId);
        threadPoolTaskScheduler.schedule(scheduledTaskJob,
        		scheduledTaskJob.getTrigger());
        scheduledTaskJob.getScheduledTask().updateTaskToStart();
        scheduledTaskJobs.put(scheduledTask.getTaskKey(), scheduledTaskJob);
    }
    
    @Override
    public void updateServiceToStop() {
    	startedFlag.set(false);
    }

}
